﻿namespace assignment4_1
{
    internal class Program1
    {
        //链表节点
        public class Node<T>
        {
            public Node<T> Next { get; set; }
            public T Data { get; set; }

            public Node(T t)
            {
                Next = null;
                Data = t;
            }
        }

        // 泛型链表类
        public class GenericList<T>
        {
            private Node<T> head;
            private Node<T> tail;

            public GenericList()
            {
                tail = head = null;
            }

            public Node<T> Head
            {
                get => head;
            }

            public void Add(T t)
            {
                Node<T> n = new Node<T>(t);
                if (tail == null)
                {
                    head = tail = n;
                }
                else
                {
                    tail.Next = n;
                    tail = n;
                }
            }

            public void ForEach(Action<T> action)
            {
                if (head == null)
                {
                    Console.Write("空链表错误");
                    return;
                }

                Node<T> current = head;
                while (current != null)
                {
                    action(current.Data);
                    current = current.Next;
                }
            }
        }

        private static void Main(string[] args)
        {
            // 整型List
            GenericList<int> intlist = new GenericList<int>();
            for (int x = 0; x < 10; x++)
            {
                intlist.Add(x);
            }

            /*
            for (Node<int> node = intlist.Head; node != null; node = node.Next)
            {
                Console.WriteLine(node.Data);
            }*/

            Console.WriteLine("使用ForEach打印元素：");
            intlist.ForEach(x => Console.WriteLine(x));

            int sum = 0;
            intlist.ForEach(x => sum += x);
            Console.WriteLine($"使用ForEach求和：{sum}");

            int max = 0;
            intlist.ForEach(x => { if (x > max) max = x; });
            Console.WriteLine($"使用ForEach求最大值：{max}");

            int min = 0;
            intlist.ForEach(x => { if (x < min) min = x; });
            Console.WriteLine($"使用ForEach求最小值：{min}");

            /*
            // 字符串型List
            GenericList<string> strList = new GenericList<string>();
            for (int x = 0; x < 10; x++)
            {
                strList.Add("str" + x);
            }
            for (Node<string> node = strList.Head; node != null; node = node.Next)
            {
                Console.WriteLine(node.Data);
            }
            */
        }
    }
}